package com.datareport.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.datareport.common.response.Result;
import com.datareport.domain.dto.StatRuleDTO;
import com.datareport.domain.entity.StatRule;
import com.datareport.service.RuleService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 规则配置控制器
 */
@RestController
@RequestMapping("/rule")
public class RuleController {
    @Autowired
    private RuleService ruleService;
    
    /**
     * 创建统计规则
     */
    @PostMapping
    public Result<String> createRule(@Valid @RequestBody StatRuleDTO ruleDTO) {
        StatRule rule = new StatRule();
        BeanUtils.copyProperties(ruleDTO, rule);
        String ruleId = ruleService.createRule(rule);
        return Result.success("创建规则成功", ruleId);
    }
    
    /**
     * 更新统计规则
     */
    @PutMapping("/{ruleId}")
    public Result<String> updateRule(@PathVariable String ruleId, @Valid @RequestBody StatRuleDTO ruleDTO) {
        StatRule rule = new StatRule();
        BeanUtils.copyProperties(ruleDTO, rule);
        rule.setRuleId(ruleId);
        ruleService.updateRule(rule);
        return Result.success("更新规则成功");
    }
    
    /**
     * 更新规则状态
     */
    @PutMapping("/{ruleId}/status")
    public Result<String> updateRuleStatus(@PathVariable String ruleId, @RequestParam Integer status) {
        ruleService.updateRuleStatus(ruleId, status);
        return Result.success("更新规则状态成功");
    }
    
    /**
     * 删除规则
     */
    @DeleteMapping("/{ruleId}")
    public Result<String> deleteRule(@PathVariable String ruleId) {
        ruleService.deleteRule(ruleId);
        return Result.success("删除规则成功");
    }
    
    /**
     * 获取规则详情
     */
    @GetMapping("/{ruleId}")
    public Result<StatRule> getRule(@PathVariable String ruleId) {
        StatRule rule = ruleService.getRule(ruleId);
        return Result.success(rule);
    }
    
    /**
     * 分页查询规则列表
     */
    @GetMapping
    public Result<Page<StatRule>> listRules(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status) {
        Page<StatRule> rules = ruleService.listRules(page, size, name, status);
        return Result.success(rules);
    }
}